﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinFormStore.实体库;
using WinFormStore.数据层;

namespace WinFormStore.ScannerSerialPro
{
    public partial class FrmPort : Form
    {
        private string path;
        private ScannerInfo scannerInfo;
        private ScannerInfoService infoService;
        public FrmPort(string path, ScannerInfo scannerInfo, ScannerInfoService infoService)
        {
            InitializeComponent();
            this.cmbPort.Items.AddRange(SerialPort.GetPortNames());
            this.cmbBaudrate.Items.AddRange(new string[] { "9600", "19200" });
            this.cmbParity.Items.AddRange(Enum.GetNames(typeof(Parity)));
            this.cmbDataBits.Items.AddRange(new string[] { "7", "8" });
            this.cmbStopbits.Items.AddRange(Enum.GetNames(typeof(StopBits)));
            this.path = path;
            this.scannerInfo = scannerInfo;
            this.infoService = infoService;
            if (this.scannerInfo != null)
            {
                this.cmbPort.Text = this.scannerInfo.PortName;
                this.cmbBaudrate.Text = this.scannerInfo.BaudRate.ToString();
                this.cmbParity.Text = this.scannerInfo.Parity.ToString();
                this.cmbDataBits.Text = this.scannerInfo.DataBits.ToString();
                this.cmbStopbits.Text = this.scannerInfo.StopBits.ToString();
            }
        }


        private void btnOK_Click(object sender, EventArgs e)
        {
            if (this.scannerInfo == null) this.scannerInfo = new ScannerInfo();
            this.scannerInfo.PortName = this.cmbPort.Text.Trim();
            this.scannerInfo.BaudRate = Convert.ToInt32(
                this.cmbBaudrate.Text.Trim());
            this.scannerInfo.Parity = (Parity)Enum.Parse(typeof(Parity),
                this.cmbParity.Text.Trim(), true);
            this.scannerInfo.DataBits = Convert.ToInt32(
                this.cmbDataBits.Text.Trim());
            this.scannerInfo.StopBits = (StopBits)Enum.Parse(typeof(StopBits), this.cmbStopbits.Text.Trim(), true);
            bool result = this.infoService.SetScannerInfoToPath(this.scannerInfo, this.path);
            if (result)
            {
                this.DialogResult = DialogResult.OK;
                MessageBox.Show("配置信息保存成功", "保存配置");
            }
            else
            {
                MessageBox.Show("配置信息保存失败", "保存配置");
            }
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }
    }
}
